package org.electronic.registration.service;

import org.electronic.registration.bo.Doctor;
import org.electronic.registration.bo.Scheduler;
import org.electronic.registration.dao.SchedulerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * User: Egor
 * Date: 08.12.11
 */
@Service("schedulerService")
public class SchedulerServiceImpl implements SchedulerService {

    @Autowired
    SchedulerDao schedulerDao;

    public void save(Scheduler scheduler) {
        schedulerDao.save(scheduler);
    }

    public List<Scheduler> getDoctorScheduler(Doctor doctor) {
        return schedulerDao.getDoctorScheduler(doctor);
    }

    @Cacheable(value = "scheduler", key = "doctor")
    public List<List<Scheduler>> generateSchedulerForDoctor(Doctor doctor) {
        List<List<Scheduler>> schedulerForDoctor = new ArrayList<List<Scheduler>>();
        Calendar calendar = new GregorianCalendar();
        Calendar today =
                new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 8, 0);
        List<Scheduler> scheduler = schedulerDao.getDoctorSchedulerFromDate(doctor, today.getTime());
        int dayOfYear = today.get(Calendar.DAY_OF_YEAR);
        List<Scheduler> schedulersForDay = new ArrayList<Scheduler>();
        for (Scheduler sch : scheduler) {
            Calendar date = new GregorianCalendar();
            date.setTime(sch.getStartDate());
            if (dayOfYear != date.get(Calendar.DAY_OF_YEAR) && schedulersForDay.size() != 0) {
                schedulerForDoctor.add(schedulersForDay);
                schedulersForDay = new ArrayList<Scheduler>();
                dayOfYear = date.get(Calendar.DAY_OF_YEAR);
            }
            schedulersForDay.add(sch);
        }
        schedulerForDoctor.add(schedulersForDay);

        return schedulerForDoctor;
    }

}
